package com.yong.automoguding.component;

import com.alibaba.fastjson.JSON;
import com.yong.automoguding.exception.MogudingException;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.CallAdapter;
import retrofit2.Converter;
import retrofit2.Retrofit;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.Objects;

/**
 * @author Hes
 */

@Slf4j
public class FastJsonRetrofitConverterFactory extends retrofit2.Converter.Factory {

    private static final MediaType HTML = MediaType.get("text/html; charset=UTF-8");

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {


        return (Converter<ResponseBody, Object>) responseBody -> {
            String jsonStr = responseBody.string();
            MediaType mediaType = responseBody.contentType();
            log.info("response contentType: {}",mediaType);
            if (Objects.equals(mediaType, HTML)) {
                throw new MogudingException("接口返回了非json数据！");
            }
            responseBody.close();
            return JSON.parseObject(jsonStr, type);
        };
    }
    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
        return (Converter<Object, RequestBody>) o -> {
            String string = JSON.toJSONString(o);

            return RequestBody.create(MediaType.get("application/json"), string);
        };
    }

}
